<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <template #footer>
      <a-button @click="closeDrawer">取消</a-button>
      <a-button type="primary" @click="handleSubmit(false)"> 保存 </a-button>
      <a-button type="primary" v-if="!isUpdate" @click="handleSubmit(true)">
        保存并继续添加
      </a-button>
    </template>
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
import { defineComponent, ref, computed, unref } from 'vue';
import { BasicForm, useForm } from '@/components/Form/index';
import { formSchema } from './menu.data';
import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
import { useMessage } from '@/hooks/web/useMessage';
import { getMenuList, editMenu, addMenu } from '@/api/sys/system';
import { useI18n } from '@/hooks/web/useI18n';
import { useDebounceFn, useThrottleFn } from '@vueuse/shared';

export default defineComponent({
  name: 'MenuDrawer',
  components: { BasicDrawer, BasicForm },
  emits: ['success', 'register'],
  setup(_, { emit }) {
    const { t } = useI18n();
    let isUpdate = ref(true);
    const { createMessage } = useMessage();
    const [
      registerForm,
      { resetFields, setFieldsValue, updateSchema, validate },
    ] = useForm({
      labelWidth: 100,
      schemas: formSchema,
      showActionButtonGroup: false,
      baseColProps: { lg: 12, md: 24 },
    });

    const [registerDrawer, { setDrawerProps, closeDrawer, changeLoading }] =
      useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
        }
        const treeData = await getMenuList();
        updateSchema({
          field: 'pid',
          label: '上级菜单',
          replaceSchema: true,
          component: 'TreeSelect',
          componentProps: {
            replaceFields: {
              title: 'title',
              key: 'id',
              value: 'id',
            },
            treeData: [
              {
                id: '0',
                pid: '-1',
                title: t('根菜单'),
                children: treeData,
              },
            ],
            getPopupContainer: () => document.body,
          },
        });
      });
    const getTitle = computed(() =>
      !unref(isUpdate) ? t('新增菜单') : t('编辑菜单')
    );
    const handleSubmit = useThrottleFn(doSubmit, 1000);
    async function doSubmit(hasNext) {
      try {
        const values = await validate();
        changeLoading(true);
        if (unref(isUpdate)) {
          await editMenu(values);
          createMessage.success(t('更新成功'));
          closeDrawer();
          emit('success');
        } else {
          await addMenu(values);
          createMessage.success(t('保存成功'));
          emit('success');
          if (hasNext) {
            resetFields();
          } else {
            closeDrawer();
          }
        }
      } finally {
        changeLoading(false);
      }
    }

    return {
      registerDrawer,
      registerForm,
      getTitle,
      handleSubmit,
      closeDrawer,
      isUpdate,
    };
  },
});
</script>
